var menuTabs, mainTabs, mainLayout, userMiniCenter, msgWindow;
var currentTab = null;
var currentTab2 = null;
var layoutExpand = true;
var presArr = null;
var storage = null;

$(function(){
	mini.parse();
	menuTabs = mini.get("menuTabs");
	mainTabs = mini.get("mainTabs");
	mainLayout = mini.get("mainLayout");
	userMiniCenter = $("#userMiniCenter");
	storage = window.localStorage;
	
	//初始化本地存储中的常用菜单数组
	if(storage){
		if(!storage.getItem("optenMenus")){
			storage.setItem("optenMenus", JSON.stringify([]));
		}
	}else{
		mini.alert("您的浏览器版本过低，不支持本地存储功能");
	}
	
	//初始化显示日期
	$("#dateSpan").html("<i class='fa fa-calendar fa-lg'></i> "+getCurrentDate()+" "+getWeek());
	$("#dateSpan").css("margin-left", "5px");
	
	rp_ajax("rp/system/baseData/preMng/getAllPreValue",{},function(result){
		presArr = result;
	},false);
	
	//点击页签上的关闭按钮前检查是否需要提示关闭
	mainTabs.on("beforecloseclick", function(e) {
		var vc = e.tab.verifyClose;
		if(vc){
			if(vc == "1"){
				mini.confirm("确定关闭页签（"+e.tab.title+"）吗？", "来自系统的提示...",
		            function (action) {
		                if (action == "ok") {
		                	mainTabs.removeTab(e.tab);
		                }else{}
		            }
		        );
			}else{
				mainTabs.removeTab(e.tab);
			}
			e.cancel = true;
		}else{
			mainTabs.removeTab(e.tab);
		}
		e.cancel = true;
    });
	
	//给页签注册双击关闭事件
	$("#mainTabs .mini-tab").live("dblclick", function(){
		mainTabs.removeTab(mainTabs.getActiveTab());
	});

	setTopNorth();
	setFooterHtml();
    initHeadImg();
    initHomeTab();

	//头像框右键菜单
    $("#headImgDiv").bind("contextmenu", function(e){
		var menu = mini.get("headImgContextMenu");
        menu.showAtPos(e.pageX, e.pageY);
		return false;
	});
	
    userMiniCenter.mouseover(function(){
		$("#userMiniCenterCloseBtn").show();
	}).mouseout(function(){
		$("#userMiniCenterCloseBtn").hide();
	});
	
	rp_ajax("rp/system/msg/getInboxForMyMsg",{},function(result){
		var count = parseInt(result);
		if(count > 0){
			$("#weiduMsg").text(" ("+result+")");
			$("#weiduA").css("color","red");
			msgWindow = $.dialog.notice({
			    id: 'msg',
			    title: '系统提示',
			    content: "您有<a href='javascript:;' onclick='openMsgGrid()' style='color:red;'>("+result+")</a>条内部消息，请注意查收",
			    width: 200,
			    height: 100,
			    left: '100%',
			    top: '100%',
			    fixed: false,
			    drag: false,
			    resize: false,
			    max: false,
			    min: false
			});
		}
	});
	
	//顶部栏的右键菜单
	$("#headerContent").bind("contextmenu", function(e){
		var menu = mini.get("bannerContextMenu");
        menu.showAtPos(e.pageX, e.pageY);
		return false;
	});
	
	//底部栏的右键菜单
	$("#footerContent").bind("contextmenu", function(e){
		var menu = mini.get("footerContextMenu");
        menu.showAtPos(e.pageX, e.pageY);
		return false;
	});
	
	//注册键盘事件
	$(document).keydown(function(e){
		var id = e.keyCode;
		switch (id){
			case 69:
                if($("#mainTabsMenu").css("display") == "block"){
                	mainTabs.reloadTab(currentTab);
                	closeMainTabsMenu();
                }else if($("#menuTabItemMenu").css("display") == "block"){
                	menuTabs.reloadTab(currentTab2);
                	$("#menuTabItemMenu, .mini-shadow").hide();
                }else if($("#bannerContextMenu").css("display") == "block"){
                	setTopNorth();
                	$("#bannerContextMenu, .mini-shadow").hide();
                }else if($("#footerContextMenu").css("display") == "block"){
                	setFooterHtml();
                	$("#footerContextMenu, .mini-shadow").hide();
                }
                break;
			/* case 87:
				if($("#mainTabsMenu").css("display") == "block"){
					moveToNewWindow();
					closeMainTabsMenu();
                }
				break; */
			case 68:
				if($("#mainTabsMenu").css("display") == "block"){
					mainTabs.removeTab(currentTab);
					closeMainTabsMenu();
                }
				break;
		}
	});
	
});

//初始化头像
function initHeadImg(){
	rp_ajax("rp/system/userMng/getCurrentUserHeadImg",{},function(result){
		if(result != "error"){
			$("#headImg").attr("src",result);
		}else{
			$("#headImg").attr("src","rp/images/head.png");
		}
	});
}

function closeUserMiniCenter(){
	userMiniCenter.hide();
	mainLayout.updateRegion("west");
	$("#userMiniCenterShowBtn").show();
}

function showUserMiniCenter(){
	userMiniCenter.show();
	mainLayout.updateRegion("west");
	$("#userMiniCenterShowBtn").hide();
}

//隐藏主页签右键菜单
function closeMainTabsMenu(){
	$("#mainTabsMenu, .mini-shadow").hide();
}

function openUserCenter(){
	addMainTab("个人中心", "rp/system/userInfoMng/showUserCenter");
}

function openMsgGrid(){
	$("#weiduMsg").text("");
	$("#weiduA").css("color","#000");
	addMainTab("内部消息", "rp/system/msg/showMsgGrid?moduleAlias=nbxxmk");
	msgWindow.close();
}

//设置顶部栏显示元素与样式
function setTopNorth(){
	rp_ajax("rp/system/baseData/preMng/getAllPreValue",{},function(result){
		var $topNorth = mainLayout.getRegion("north");
		mainLayout.updateRegion("north",{"height" : parseInt(getPreValue("topNorthHeight", result))});
		$("#headerContent").html(getPreValue("bannerHtml", result));
	});
}

//设置底部栏显示
function setFooterHtml(){
	rp_ajax("rp/system/baseData/preMng/getAllPreValue",{},function(result){
		$("#footerText").html(getPreValue("footerText", result));
		$(".mini-layout-region-south").css("background-color", getPreValue("footerBackgroundColor", result));
	});
}

//打开编辑横幅窗
function openEditBanner(){
	mini.open({
		url: "rp/common/editBanner.jsp",
		title: "编辑横幅",
		width: 800,
		height: 390,
		onload: function () {
        	
      	},ondestroy: function (action) {
      		setTopNorth();
        }
	});
}

//打开编辑底栏
function openEditFooter(){
	mini.open({
		url: "rp/common/editFooter.jsp",
		title: "编辑底栏",
		width: 800,
		height: 390,
		onload: function () {
        	
      	},ondestroy: function (action) {
      		setFooterHtml();
        }
	});
}

//打开头像编辑框
function openUploadHeadImg(){
	mini.open({
		url: "rp/common/uploadHeadImg.jsp",
		title: "修改头像",
		width: 800,
		height: 390,
		onload: function () {
        	
      	},ondestroy: function (action) {
      		initHeadImg();
        }
	});
}

//添加页签，在主界面添加页签主要就是通过此方法
//_title：页签标题，
//_url：页签内容加载的URL地址，相对于项目跟路径，
//_verifyClose：是否校验关闭，如果校验则传入字符串1，否则传入字符串0或不传任何参数
function addMainTab(_title, _url, _verifyClose){
	var tabs = mainTabs.getTabs();
	var tabsLength = tabs.length;
	//循环判断当前队列中是否已经存在_title标题的页签，如果存在则激活它
	for(var i=0; i<tabsLength; i++){
		if(tabs[i].title == _title){
			mainTabs.activeTab(mainTabs.getTab(_title));
			return false;
		}
	}
	var tab = {title: _title, name: _title, url: _url, showCloseButton: true, verifyClose: _verifyClose};
	tab = mainTabs.addTab(tab);
	
	mainTabs.activeTab(tab);
	
	addMenuToLocalStorage(_title, _url);
}

/**
 * 添加打开的菜单至浏览器本地存储
 * @param _title
 * @param _url
 * @returns {Boolean}
 */
function addMenuToLocalStorage(_title, _url){
	var optenMenus = JSON.parse(storage.getItem("optenMenus"));
	if(optenMenus){
		var menu = {id:'', text:''};
		menu.id = _url;
		menu.text = _title;
		for(var i=0; i<optenMenus.length; i++){
			if(optenMenus[i].text === _title){
				return false;
			}
		}
		//optenMenus.push(menu);
		optenMenus.splice(0, 0, menu);
		storage.setItem("optenMenus", JSON.stringify(optenMenus));
	}
}

function onBeforeOpen(e) {
    currentTab = mainTabs.getTabByEvent(e.htmlEvent);
    if (!currentTab) {
        e.cancel = true;      
    }
}

function onBeforeOpen2(e){
	currentTab2 = menuTabs.getTabByEvent(e.htmlEvent);
    if (!currentTab2) {
        e.cancel = true;      
    }
}

//刷新菜单Tab
function reloadMenuTabsItem(){
	menuTabs.reloadTab(currentTab2);
}


//刷新标签页
function refreshTab(){
	mainTabs.reloadTab(currentTab);
}
//移动到新窗口
function moveToNewWindow(){
	//判断是否用的是IE浏览器
	if ((navigator.userAgent.indexOf('MSIE') >= 0) 
			&& (navigator.userAgent.indexOf('Opera') < 0)){
		window.open("../"+currentTab.url);
	}else{
		window.open(currentTab.url);
	}
	
}
//关闭标签页
function closeCurrentTab(){
	mainTabs.removeTab(currentTab);
}

//关闭其他标签页
function closeOtherTabs(){
	mainTabs.removeAll(currentTab);
}

//关闭右侧标签页
function closeRightTabs(){
	var currentTabName = currentTab.name;
	var tabs = mainTabs.getTabs();
	var tabsLength = tabs.length;
	var startIndex = null;
	for(var i=0; i<tabsLength; i++){
		if(tabs[i].name == currentTabName){
			startIndex = i+1;
			break;
		}
	}
	for(var i=startIndex; i<=(tabsLength-1); i++){
		mainTabs.removeTab(startIndex);
	}
}

//关闭所有标签页
function closeAllTabs(){
	mainTabs.removeAll();
}

function showURL(){
	mini.alert($("#basePath").val()+currentTab.url);
}

/*function bindEven(_title, _url){
	$("#mainTabs .mini-tab").dblclick(function(){
		var tab = mainTabs.getTab(_title);
		mainTabs.removeTab(tab);
 	});
}

function changeTheme(){
	mini.open({
		url: "changeTheme.jsp",
		width: "300",
		height: "60",
		title: "切换主题"
	});
}*/

function onSkinChange(skin){
    mini.Cookie.set("miniuiSkin", skin);
    mini.Cookie.set("miniuiSkin", skin, 100);//100天过期的话，可以保持皮肤切换
    window.parent.location.reload()
}

function initHomeTab(){
	var showHome = getPreValue("showHome", presArr);
	if(showHome == "1"){
		var homeUrl = getPreValue("homeUrl", presArr);
		if(homeUrl){
			addMainTab("首页", homeUrl);
		}
	}
}

function loadHome(){
	var homeUrl = getPreValue("homeUrl", presArr);
	if(homeUrl){
		addMainTab("首页", homeUrl);
	}
}

function changePassword(){
	mini.open({
		url: "rp/system/userMng/showChangePwdWindow?userId="+$("#userId").val(),
		title: "修改密码",
		width: 300,
		height: 200,
		ondestroy: function (action) {
            if (action == "ok") {
            	
            }
        }
	});
}

function logout(){
	mini.confirm("确定退出系统吗？", "来自系统的提示...",
        function(action){
        	if (action == "ok") {
        		//判断是否用的是IE浏览器
        		if ((navigator.userAgent.indexOf('MSIE') >= 0) 
    					&& (navigator.userAgent.indexOf('Opera') < 0)){
        			window.location = "logout";
    			}else{
    				window.location = "rp/logout";
    			}
            }else{
              
            }
        }
    );
}

//收展顶部栏
function toggleHeader(){
	var isExpand = mainLayout.isExpandRegion("north");
	if(isExpand){
		mainLayout.updateRegion("north", {expanded: false});
		showUserMiniCenter();
	}else{
		mainLayout.updateRegion("north", {expanded: true});
		closeUserMiniCenter();
	}
}

//收展侧边栏
function toggleSidebar(){
	var isExpand = mainLayout.isExpandRegion("west");
	if(isExpand){
		mainLayout.updateRegion("west", {expanded: false});
	}else{
		mainLayout.updateRegion("west", {expanded: true});
	}
}

//全屏显示应用
function fullScreen(){
	var docElm = document.documentElement;
    if(docElm.requestFullscreen){
    	docElm.requestFullscreen();
    }else if(docElm.mozRequestFullScreen){
    	docElm.mozRequestFullScreen();  
    }else if(docElm.webkitRequestFullScreen){
    	docElm.webkitRequestFullScreen();  
    }else if(docElm.msRequestFullscreen){
    	docElm.msRequestFullscreen();
    }else{
    	alert("当前浏览器不支持此操作");
    }
}

function packUpAllLayout(){
	if(layoutExpand){
		mainLayout.updateRegion("north", {expanded: false});
		mainLayout.updateRegion("west", {expanded: false});
		layoutExpand = false;
	}else{
		mainLayout.updateRegion("north", {expanded: true});
		mainLayout.updateRegion("west", {expanded: true});
		layoutExpand = true;
	}
}

function oftenMenuComboboxItemclick(e){
	var item = e.item;
	addMainTab(item.text, item.id);
}

function oftenMenuComboboxBeforeShow(e){
	var oftenMenuCombobox = mini.get("oftenMenuCombobox");
	oftenMenuCombobox.load(JSON.parse(storage.getItem("optenMenus")));
}

function mainTabsbeforeactivechanged(e){
	var oftenMenuCombobox = mini.get("oftenMenuCombobox");
	oftenMenuCombobox.setValue(null);
}